package pers.elonnsu.springbootmall.controller;

import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import pers.elonnsu.springbootmall.common.ApiRestResponse;
import pers.elonnsu.springbootmall.common.Constant;
import pers.elonnsu.springbootmall.exception.MallException;
import pers.elonnsu.springbootmall.exception.MallExceptionEnum;
import pers.elonnsu.springbootmall.model.pojo.Product;
import pers.elonnsu.springbootmall.model.request.AddProductReq;
import pers.elonnsu.springbootmall.model.request.UpdateProductReq;
import pers.elonnsu.springbootmall.service.ProductService;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Objects;
import java.util.UUID;

@RestController
public class ProductAdminController {
    @Autowired
    private ProductService productService;

    @ApiOperation("后台：新增商品")
    @PostMapping("/admin/product/add")
    public ApiRestResponse<Object> addProduct(@Valid AddProductReq addProductReq) {
        productService.add(addProductReq);
        return ApiRestResponse.success();
    }

    @ApiOperation("后台：更新商品")
    @PostMapping("/admin/product/update")
    public ApiRestResponse<Object> updateProduct(@Valid @RequestBody UpdateProductReq updateProductReq) {
        Product product = new Product();
        BeanUtils.copyProperties(updateProductReq, product);
        productService.update(product);
        return ApiRestResponse.success();
    }

    @ApiOperation("后台：删除商品")
    @PostMapping("/admin/product/delete")
    public ApiRestResponse<Object> deleteProduct(Integer id) {
        productService.delete(id);
        return ApiRestResponse.success();
    }

    @ApiOperation("后台：批量上下架商品")
    @PostMapping("/admin/product/batchUpdateSellStatus")
    public ApiRestResponse<Object> batchUpdateSellStatus(@RequestParam Integer[] ids, @RequestParam Integer sellStatus) {
        productService.batchUpdateSellStatus(ids, sellStatus);
        return ApiRestResponse.success();
    }

    @ApiOperation("后台：获取后台商品列表")
    @GetMapping("/admin/product/list")
    public ApiRestResponse<Object> list(@RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize") Integer pageSize) {
        PageInfo<Product> productPageInfo = productService.listForAdmin(pageNum, pageSize);
        return ApiRestResponse.success(productPageInfo);
    }

    @ApiOperation("后台：上传图片")
    @PostMapping("/admin/product/file")
    public ApiRestResponse<Object> upload(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        String filename = file.getOriginalFilename();
        String suffix = Objects.requireNonNull(filename).substring(filename.lastIndexOf("."));
        // 生成文件名称UUID
        UUID uuid = UUID.randomUUID();
        String newFileName = uuid + suffix;
        // 创建文件
        File fileDirectory = new File(Constant.FILE_UPLOAD_DIR);
        File destFile = new File(Constant.FILE_UPLOAD_DIR + newFileName);
        if (!fileDirectory.exists()) {
            if (!fileDirectory.mkdir()) {
                throw new MallException(MallExceptionEnum.MKDIR_FAILED);
            }
        }

        try {
            file.transferTo(destFile);
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            URI uri = new URI(request.getRequestURL() + "");
            String url = getHost(uri) + Constant.SERVLET_CONTEXT_PATH + "/images/" + newFileName;
            return ApiRestResponse.success(url);
        } catch (URISyntaxException e) {
            return ApiRestResponse.error(MallExceptionEnum.UPLOAD_FAILED);
        }
    }

    private URI getHost(URI uri) {
        URI effectiveURI;
        try {
            effectiveURI = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), null, null, null);
        } catch (URISyntaxException e) {
            effectiveURI = null;
            e.printStackTrace();
        }
        return effectiveURI;
    }
}
